import { ref, shallowRef } from "vue";
import { defineStore } from "pinia";
import type { ShallowRef, Ref } from "vue";
import type { BannerItemVO, CategoryItemVO, GuessItemVO, HotItemVO, PageDTO } from "@/types/homeType";
import type { Page } from "@/types/response";
import { fetchBannerListAPI, fetchGuessListAPI, fetchHotListAPI, fetchNavListAPI, fetchNewListAPI } from "@/api/homeApi";

const useHomeStore = defineStore("homeStore", () => {
   // 轮播图数组
   const bannerList: ShallowRef<BannerItemVO[]> = shallowRef<BannerItemVO[]>([]);
   // 分类导航数组
   const navList: ShallowRef<CategoryItemVO[]> = shallowRef<CategoryItemVO[]>([]);
   // 热门推荐的数组
   const hotList: ShallowRef<HotItemVO[]> = shallowRef<HotItemVO[]>([]);
   // 猜你喜欢的数组
   const guessList: Ref<GuessItemVO[]> = ref<GuessItemVO[]>([]);
   const total: ShallowRef<number> = shallowRef<number>(1);
   // 新鲜好物的数组
   const newList: ShallowRef<GuessItemVO[]> = shallowRef<GuessItemVO[]>([]);
   // 发送请求获取轮播图的回调函数
   const fetchBannerList = async (distributionSite: number = 1):Promise<void> => {
      try {
         const { result }: { result: BannerItemVO[] } = await fetchBannerListAPI(distributionSite);
         bannerList.value = result;
         bannerList.value = result;
      } catch (error: any) {
         await error;
      }
   };
   // 发送请求获取分类导航的回调函数
   const fetchNavList = async ():Promise<void> => {
      try {
         const { result }: { result: CategoryItemVO[] } = await fetchNavListAPI();
         navList.value = result;
      } catch (error: any) {
         await error;
      }
   };
   // 发送请求获取热门推荐的回调函数
   const fetchHotList = async ():Promise<void> => {
      try {
         const { result }: { result: HotItemVO[] } = await fetchHotListAPI();
         hotList.value = result;
      } catch (error: any) {
         await error;
      }
   };
   // 发送请求获取猜你喜欢的回调函数
   const fetchGuessList = async (page: PageDTO):Promise<void> => {
      try {
         if (guessList.value.length >= total.value) {
            await uni.showToast({ title: "数据加载完毕", icon: "success" });
         } else {
            const { result }: { result: Page<GuessItemVO[]> } = await fetchGuessListAPI(page);
            guessList.value.push(...result.items);
            total.value = result.counts;
            page.page += 1;
         }
      } catch (error: any) {
         await error;
      }
   };
   // 发送请求获取新鲜好物的回调函数
   const fetchNewList = async (limit: number):Promise<void> => {
      try {
         const { result }: { result: GuessItemVO[] } = await fetchNewListAPI(limit);
         newList.value = result;
      } catch (error: any) {
         await error;
      }
   };
   return {
      bannerList,
      fetchBannerList,
      navList,
      fetchNavList,
      hotList,
      fetchHotList,
      guessList,
      total,
      fetchGuessList,
      newList,
      fetchNewList,
   };
});


export default useHomeStore;